package com.ibeetl.cms.web;

import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.util.ConvertUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.cms.entity.EssentialInformation;
import com.ibeetl.cms.entity.Quit;
import com.ibeetl.cms.service.*;
import com.ibeetl.cms.util.BusinessTypeConstant;
import com.ibeetl.cms.util.ProcessConstant;
import com.ibeetl.cms.web.query.QuitQuery;
import com.ibeetl.cms.web.query2.QuitEnterpriseQuery;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Quit 接口
 */
@Controller
public class QuitController{

    private final Log log = LogFactory.getLog(this.getClass());
    private static final String MODEL = "/cms/quit";


    @Autowired private QuitService quitService;

    @Autowired
    CorePlatformService platformService;

    @Autowired
    private EssentialInformationService essentialInformationService;


    @Autowired
    private BusinessProcessService businessProcessService;

    @Autowired private EnterpriseService enterpriseService;

    @Autowired private EntryService entryService;
    
    @Autowired
    FileService fileService;
    /* 页面 */

    @GetMapping(MODEL + "/index.do")
    @Function("quit")
    @ResponseBody
    public ModelAndView index() {
        ModelAndView view = new ModelAndView("/cms/quit/index.html") ;
        view.addObject("search", QuitQuery.class.getName());
        return view;
    }

    @GetMapping(MODEL + "/enterprise.do")
    @Function("quit.company")
    @ResponseBody
    public ModelAndView enterprise() {
        ModelAndView view = new ModelAndView("/cms/quit/enterprise.html") ;
        view.addObject("search", QuitEnterpriseQuery.class.getName());
        return view;
    }

    @GetMapping(MODEL + "/edit.do")
    @Function("quit")
    @ResponseBody
    public ModelAndView edit(Integer id) {
        ModelAndView view = new ModelAndView("/cms/quit/edit.html");
        Quit quit = quitService.queryById(id);
        view.addObject("quit", quit);
        return view;
    }

    @GetMapping(MODEL + "/add.do")
    @Function("quit")
    @ResponseBody
    public ModelAndView add() {
        ModelAndView view = new ModelAndView("/cms/quit/add.html");
        Long userid = getUserId();
        EssentialInformation essentialInformation = essentialInformationService.finduserid(userid);
        view.addObject("basic", essentialInformation);
        return view;
    }

    /* ajax json */

    @PostMapping(MODEL + "/list.json")
    @Function("quit")
    @ResponseBody
    public JsonResult<PageQuery> list(QuitQuery condtion)
    {
        PageQuery page = condtion.getPageQuery();
        Integer year = Calendar.getInstance().get(Calendar.YEAR);
        condtion.setYear( year.toString());
        condtion.setUserId(getUserId());
        quitService.queryByCondition(page);
        return JsonResult.success(page);
    }

    @PostMapping(MODEL + "/Acceptancelist.json")
    @Function("quit.company")
    @ResponseBody
    public JsonResult<PageQuery> Acceptancelist(QuitQuery condtion)
    {
        Long userid=getUserId();
        Integer year = Calendar.getInstance().get(Calendar.YEAR);
        condtion.setYear( year.toString());
        condtion.setUserId(userid);

        condtion.setCompanyId(userid.toString());
        if(condtion.getBusinessState()=="" || condtion.getBusinessState()==null){
            condtion.setBusinessState(ProcessConstant.TO_COMPANY);
        }else {
            condtion.setBusinessState(condtion.getBusinessState());
        }
        //查询企业数据
        PageQuery page = condtion.getPageQuery();
        quitService.findenterprise(page);
        return JsonResult.success(page);
    }

    /**
     * 新增（保存）
     * @param quit
     * @return
     */
    @PostMapping(MODEL + "/add.json")
    @Function("quit")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)Quit quit)
    {
        Integer year = Calendar.getInstance().get(Calendar.YEAR);
        String yearStr = year.toString();
        quit.setYear(yearStr);

        Long userId = getUserId();
        quit.setUserId(userId.intValue());
        quit.setCreationDate(new Date());
        quit.setCompanyId(Math.toIntExact(platformService.getCurrentUser().getCompanyId()));
        quit.setBusinessState(ProcessConstant.WAIT_APPLICATION_STR);
        quit.setBusinessStateCode(ProcessConstant.WAIT_APPLICATION);

        quitService.save(quit);
        //调用增加业务流程数据
        businessProcessService.processInformation(quit.getId(),quit.getBusinessState(),
                quit.getBusinessStateCode(),quit.getHandlingSuggestion(),"成功", BusinessTypeConstant.quit);
        return new JsonResult().success();
    }

    /**
     * 新增（保存并申请）
     *
     * @param quit
     * @return
     */
    @PostMapping(MODEL + "/savedeclaration.json")
    @Function("quit")
    @ResponseBody
    public JsonResult savedeclaration(@Validated(ValidateConfig.ADD.class) Quit quit) {
        Integer year = Calendar.getInstance().get(Calendar.YEAR);
        String yearStr = year.toString();

        Long userId = getUserId();
        quit.setUserId(userId.intValue());
        quit.setCreationDate(new Date());
        quit.setDateReporting(new Date());
        quit.setBusinessState(ProcessConstant.TO_COMPANY_STR);
        quit.setBusinessStateCode(ProcessConstant.TO_COMPANY);
        quit.setCompanyId(Math.toIntExact(platformService.getCurrentUser().getCompanyId()));
        quit.setYear(yearStr);

        quitService.save(quit);

        //调用增加业务流程数据
        businessProcessService.processInformation(quit.getId(),quit.getBusinessState(),
                quit.getBusinessStateCode(),quit.getHandlingSuggestion(),"成功", BusinessTypeConstant.quit);
        return new JsonResult().success();
    }


    /**
     * 修改（保存）
     * @param quit
     * @return
     */
    @PostMapping(MODEL + "/update.json")
    @Function("quit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  Quit quit) {
        quit.setBusinessState(ProcessConstant.WAIT_APPLICATION_STR);
        quit.setBusinessStateCode(ProcessConstant.WAIT_APPLICATION);
        boolean success = quitService.updateTemplate(quit);

        if (success) {
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    /**
     * 修改（保存并申请）
     *
     * @param quit
     * @return
     */
    @PostMapping(MODEL + "/editandsave.json")
    @Function("quit")
    @ResponseBody
    public JsonResult<String> editandsave(@Validated(ValidateConfig.UPDATE.class)  Quit quit) {
        quit.setDateReporting(new Date());

        quit.setBusinessState(ProcessConstant.TO_COMPANY_STR);
        quit.setBusinessStateCode(ProcessConstant.TO_COMPANY);

        boolean success = quitService.updateTemplate(quit);

        if (success) {
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }


   
    @GetMapping(MODEL + "/view.json")
    @Function("cms.quit.query")
    @ResponseBody
    public JsonResult<Quit>queryInfo(Integer id) {
        Quit quit = quitService.queryById( id);
        return  JsonResult.success(quit);
    }

    @PostMapping(MODEL + "/delete.json")
    @Function("quit")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        List<Long> idList = ConvertUtil.str2longs(ids);
        quitService.batchDelQuit(idList);
        return new JsonResult().success();
    }

    /**
     * 查看页面跳转
     *
     * @return
     */
    @GetMapping(MODEL + "/findenterprise.do")
    @ResponseBody
    public ModelAndView findenterprise(Integer id) {
        ModelAndView view = new ModelAndView("/cms/quit/findenterpriseedit.html");
        Quit quit = quitService.queryById(id);
        view.addObject("look",true);
        view.addObject("quit", quit);
        return view;
    }

    @PostMapping(MODEL + "/firstcheckList.json")
    @ResponseBody
    public JsonResult<PageQuery> firstcheckList(QuitQuery condtion) {
        /**
         * 获得本年度已办任务
         */
        if(condtion.getYear()=="" || condtion.getYear()==null) {
            Integer year = Calendar.getInstance().get(Calendar.YEAR);
            condtion.setYear(year.toString());
        }
        condtion.setProcessUserId(getUserId());
        condtion.setBusinessType(BusinessTypeConstant.quit);
        PageQuery page = condtion.getPageQuery();
        quitService.queryDoneTask(page);
        return JsonResult.success(page);
    }

    /**
     * 单位产业人才点击受理页面跳转
     *
     * @return
     */
    @GetMapping(MODEL + "/acceptance.do")
    @Function("quit.company")
    @ResponseBody
    public ModelAndView acceptance(Integer id) {
        ModelAndView view = new ModelAndView("/cms/quit/acceptance.html");
        Quit quit = quitService.queryById(id);
        view.addObject("quit", quit);
        return view;
    }

    /**
     * 终止功能
     */
    @PostMapping(MODEL + "/Acceptancelisttermination.json")
    @Function("quit.company")
    @ResponseBody
    public JsonResult<String> Acceptancelisttermination(@Validated(ValidateConfig.UPDATE.class) Quit quit) {
        quit.setBusinessState(ProcessConstant.TERMINIATE_STR);
        quit.setBusinessStateCode(ProcessConstant.TERMINIATE);
        boolean success = quitService.updateTemplate(quit);
        String result;
        if (success) {
            result=ProcessConstant.TERMINIATE_STR;
        } else {
            result="失败";
        }
        //调用增加业务流程数据
        businessProcessService.processInformation(quit.getId(),quit.getBusinessState(),
                quit.getBusinessStateCode(),quit.getHandlingSuggestion(),result,BusinessTypeConstant.quit);
        return new JsonResult().success();
    }

    /**
     * 退回功能
     */
    @PostMapping(MODEL + "/Acceptancelistterreturn.json")
    @Function("quit.company")
    @ResponseBody
    public JsonResult<String> Acceptancelistterreturn(@Validated(ValidateConfig.UPDATE.class) Quit quit) {
            quit.setBusinessState(ProcessConstant.RETURN_DECLARATION_STR);
            quit.setBusinessStateCode(ProcessConstant.RETURN_DECLARATION);
        boolean success = quitService.updateTemplate(quit);
        String result;
        if (success) {
            result=ProcessConstant.COMPANY_BACK_STR;
        } else {
            result="失败";
        }
        //调用增加业务流程数据
        businessProcessService.processInformation(quit.getId(),quit.getBusinessState(),
                quit.getBusinessStateCode(),quit.getHandlingSuggestion(),result,BusinessTypeConstant.quit);
        return new JsonResult().success();
    }

    /**
     * 通过功能
     */
    @PostMapping(MODEL + "/Acceptancelistsuccess.json")
    @Function("quit.company")
    @ResponseBody
    public JsonResult<String> Acceptancelistsuccess(@Validated(ValidateConfig.UPDATE.class) Quit quit) {
            quit.setBusinessState(ProcessConstant.DONE_STR);
            quit.setBusinessStateCode(ProcessConstant.DONE);
        boolean success = quitService.updateTemplate(quit);
        String result;
        if (success) {
            quitService.updateCompanyId(quit.getUserId());//离职后修改用户企业id为0
            result=ProcessConstant.COMPANY_ADOPT_STR;
        } else {
            result="失败";
        }
        //调用增加业务流程数据
        businessProcessService.processInformation(quit.getId(),quit.getBusinessState(),
                quit.getBusinessStateCode(),quit.getHandlingSuggestion(),result,BusinessTypeConstant.quit);
        return new JsonResult().success();
    }


    /**
     * 公共方法
     * 用于获取登录ID
     *
     * @return
     */
    public Long getUserId() {
        CoreUser currentUser = platformService.getCurrentUser();
        Long userId = currentUser.getId();
        return userId;
    }
}
